/*
 *  Copyright (C) 2009 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Monitoring;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;

import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.User;
import com.LibreGeoSocial.App.R;
import com.LibreGeoSocial.App.Overlay.PositionOverlay;
import com.LibreGeoSocial.App.Utils.MapUtils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MonitoringMap extends MapActivity 
{
	
	private MapView mapView;
	MapController mapControl;
	   
	private GeoPoint point;
	   
	private User monitoringUser;
	
	// Power Manager
	protected PowerManager.WakeLock mWakeLock; 
	
	// Timer
	private Timer mTimer = null;
	
	private Location locationPerimeter;
	   
	@Override
    public void onCreate(Bundle icicle) {
		   
		   super.onCreate(icicle);
		   
		   final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
		   this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "label_screen"); 
		   this.mWakeLock.acquire();
		   
		   FrameLayout frame = new FrameLayout(this);
		   
		   mapView = new MapView(this, getString(R.string.map_key));
		   mapControl = mapView.getController();
		   

	       frame.addView(mapView, 
	                new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

	       
		   setContentView(frame);		  
		   
		   /* Obtain data */
		   Intent i = getIntent();
		   Integer userId = i.getIntExtra("userId", -1);
		   
		   monitoringUser =  LibreGeoSocial.getInstance().getInfoUser(true, userId);
		   getUserPositionAndCenterMap();
		   
		   locationPerimeter = monitoringUser.getLocation();
		  
		   showUserAndPerimeter();
	       
		   mapView.setOnTouchListener(touchListener);
		   
	       /* Settings map */
	       mapView.setClickable(true);
	       mapView.setEnabled(true);
	       mapView.setSatellite(false);

	       addZoomControls(frame);
	       
	       launchTask();

	}
	
    @Override
    public void onDestroy() {
         this.mWakeLock.release();
         
 		// Stop timer
 		if (mTimer!=null)
 		{
 			mTimer.cancel();
 			mTimer = null;
 		}
         
        super.onDestroy();
    } 
    
    private OnTouchListener touchListener = new OnTouchListener()
    {
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			
			switch(event.getAction()){
			
			case MotionEvent.ACTION_DOWN:

				break;
				
			case MotionEvent.ACTION_MOVE:
				GeoPoint new_map_center = mapView.getMapCenter();
		    	
		    	//double distance = Math.sqrt(Math.pow(new_map_center.getLatitudeE6()-map_center.getLatitudeE6(),2)+
		    	//		Math.pow(new_map_center.getLongitudeE6()-map_center.getLongitudeE6(),2));
		    	
		    	//map_center = new_map_center; 

		    	
				break;
			
			case MotionEvent.ACTION_UP:
				
				locationPerimeter = MapUtils.getLocFromXY(event.getX(), event.getY(), mapView, 0);
				showUserAndPerimeter();
				
				break;
				
			default:
					break;
			}
			
			return false;
		}
	
	};
	
    private void showUserAndPerimeter ()
    {
		   PositionOverlay myposOverlay = new PositionOverlay();  
		   myposOverlay.setUser(monitoringUser);
		   myposOverlay.withPerimeter(locationPerimeter);
		   
		   mapView.getOverlays().clear();
		   
	       final List<Overlay> overlays = mapView.getOverlays();
	       overlays.add(myposOverlay);  
	       
	       mapView.invalidate();
    }
    
    /* Maps method */
	private void getUserPositionAndCenterMap ()
	{		
		monitoringUser =  LibreGeoSocial.getInstance().getInfoUser(true, monitoringUser.getId());
		   
		   point = new GeoPoint((int) (monitoringUser.getLatitude() * 1000000), (int) (monitoringUser.getLongitude()* 1000000));
		   mapControl.setZoom(18);
		   mapControl.setCenter(point);		   
	}
	   	
    private void addZoomControls(FrameLayout frame) {
        View zoomControls = mapView.getZoomControls();

        FrameLayout.LayoutParams p = 
            new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
        frame.addView(zoomControls, p);
    }
	    
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	/* */
	
    private void launchTask()
    {    	
    
    	int delay = 1000;   // delay for 1 seconds
    	int period = 5000;
        //int period = ((LocationPeriodic)* 1000) * LocationUnit;  // in mili-seconds
		
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() { 
            	
            	handler_ProgressDiaglog.sendEmptyMessage(0);
            }
        }, delay, period);

    }
    
	/* Handler to show the new friend position */
	private Handler handler_ProgressDiaglog = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			getUserPositionAndCenterMap();
				    	
		}
	};

}
